//
//  BlockWithAutoVar.m
//  block
//
//  Created by Mac on 16/3/19.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "BlockWithAutoVar.h"
#import "Person.h"
@implementation BlockWithAutoVar
/*
 当block定义在方法内部时:(可以看做是block作为方法的局部变量)
 1. block可以直接访问自动变量，包括基本类型和对象类型的自动变量
 2. block可以修改带__block修饰符的自动变量。包括基本类型和对象类型的自动变量。在block之后被修改的自动变量的值也会改变。修改对象类型的自动变量是指给对象的引用另外赋值:
    例如在block之前: __block Person *p = [[Person alloc] initWithName:@"apple"];
    在block中, p = [[Person alloc] initWithName: @"banana"];
    在block后, p.name = @"banana";
 3. block中我们可以修改不带__block修饰符的对象类型自动变量的属性:
    例如在block之前: Person *p = [[Person alloc] initWithName:@"Roger"];
    在block中, p.name = @"Jim";
    在block后, p.name = @"Jim";
 */
-(void)createBlock {
    //** 访问自动变量 PS:自动变量就是局部变量
    int a = 3;
    [self usingBlockWithBasicVar:^int(int p1, int p2) {
        return p1+p2+a; //+1+1+3=5
    }];
    
    //** 修改基本类型的自动变量 需要加上__block修饰符方能修改
    __block int b = 3;
    [self usingBlockWithBasicVar:^int(int p1, int p2) {
        b = 4;
        return p1+p2+b; //1+1+4=6
    }];
    NSLog(@"after block, b=%d", b); //4
    
    //** 访问对象类型的自动变量
    Person *person1 = [[Person alloc] initWithName:@"apple"];
    [self usingBlockWithObjectVar:^{
        NSLog(@"%@", person1.name); //apple
    }];
    
    //** 修改对象类型的自动变量 需要加上__block修饰符方能修改
    __block Person *person2 = [[Person alloc] initWithName:@"banana"];
    [self usingBlockWithObjectVar:^{
        person2 = [[Person alloc] initWithName:@"cat"];
        NSLog(@"person2's name in block = %@", person2.name); //cat
    }];
    NSLog(@"person2's name after block = %@", person2.name); //cat
    
    //** 仅改变对象类型自动变量的属性值 无需__block修饰符
    Person *person3 = [[Person alloc] initWithName:@"dog"];
    [self usingBlockWithObjectVar:^{
        person3.name = @"elephant";
        NSLog(@"person3's name in block = %@", person3.name); //elephant
    }];
    NSLog(@"person3's name after block = %@", person3.name); //elephant
}

-(void)usingBlockWithBasicVar:(int(^)(int, int))block {
    int p1 = 1;
    int p2 = 1;
    NSLog(@"%d",block(p1,p2));
}

-(void)usingBlockWithObjectVar:(void(^)())block {
    block();
}
@end
